package com.yidu.news.view;

import com.yidu.news.domain.User;
import com.yidu.news.service.UserService;
import com.yidu.news.utils.BaseMessage;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 用户的action
 */
@Controller
@RequestMapping("/user")
@PropertySource(value = {"classpath:config/conf.properties"})
public class UserController {

    @Resource
    UserService userService;



    @Value("${saveFilePath}")
    String saveFilePath ;

    /**
     * 1 SpringMVC是如何转向页面的.
     * 2 SpringMVC是如何获取页面上提交的值.
     *      1> 直接使用参数和表单中的name对应
     *      2> 直接使用一个模型,模型中的属性名和表单中的name对应
     * @return
     */

   /* @RequestMapping("/index")
    public String index(){
        return "regist";
    }

    @RequestMapping("/regist")
    public String regist(Integer userAge,String userName,String userPwd){

        System.out.println("userName = [" + userName + "], userPwd = [" + userPwd + "], userAge = [" + userAge + "],");

        //必须要匹配参数
        //如果遇到了400的错误,就是参数不合法
        return "login";
    }

    @RequestMapping("/regist2")
    public String regist2(User user){

        System.out.println("user = [" + user.getUserName() + "]");
        System.out.println("user = " + user.getRemark());
        //必须要匹配参数
        //如果遇到了400的错误,就是参数不合法
        return "login";
    }*/

    /**
     * 注册的方法
     * @return
     */
    @RequestMapping("/registSubmit")
    @ResponseBody
   public BaseMessage registSubmit(User user){

        BaseMessage baseMessage = new BaseMessage();
        int rows = userService.add(user);
        baseMessage.setState(rows);
        baseMessage.setMessage(rows==0?"注册失败!":"注册成功!");
        return baseMessage ;

   }

    /**
     * 需要上传文件
     * @param user
     * @return
     */
    @RequestMapping("/registSubmitFile")
    @ResponseBody
    public BaseMessage registSubmitFile(@RequestParam("userFile") MultipartFile mulfile, User user, HttpServletRequest request) throws IOException { //参数user里面的值只有file匹配不到

        //得到项目运行的真实路径
        //String realPath = request.getServletContext().getRealPath("/upload");


        System.out.println("真实路径是: "+saveFilePath);

        String name = mulfile.getOriginalFilename() ;//得到原文件名
        int index = name.lastIndexOf("."); //234234.4443.123.jpg
        String suf = name.substring(index);//得到后缀名
        String fileName = UUID.randomUUID().toString()+""+suf; //ffff-22221-ffff-ff.jpg

        mulfile.transferTo(new File(saveFilePath+"/"+fileName)); //保存文件

        user.setFile("upload/"+fileName);

        BaseMessage baseMessage = new BaseMessage();
        int rows = userService.add(user);
        baseMessage.setState(rows);
        baseMessage.setMessage(rows==0?"注册失败!":"注册成功!");
        return baseMessage ;

    }


   @RequestMapping("/loginSubmit")
   @ResponseBody
   public BaseMessage loginSubmit(String userName, String userPassword, HttpSession session){
       BaseMessage baseMessage = new BaseMessage();
       User user = userService.queryLogin(userName,userPassword);
       if(user==null){
           baseMessage.setState(0);
           baseMessage.setMessage("用户名和密码错误!");
       }else{
           session.setAttribute("user",user);
           baseMessage.setState(1);
           baseMessage.setMessage("登录成功!");//111133
       }
       return baseMessage;
   }

    /**
     * 检查session
     * @param session
     * @return
     */
    @RequestMapping("/checkSession")
    @ResponseBody
   public BaseMessage checkSession(HttpSession session){
        User user = (User)session.getAttribute("user");
        BaseMessage baseMessage= new BaseMessage();
        if(user==null){
            baseMessage.setState(0);
            baseMessage.setMessage("没有用户信息请登录!");
        }else{
            baseMessage.setState(1);
            baseMessage.setMessage("找到用户信息");
            baseMessage.setObj(user);
        }

        return baseMessage ;
   }

   @RequestMapping("/findAll")
   @ResponseBody
   public Map<String,Object> findAll(User user){
        Map<String,Object> map = new HashMap<String, Object>();

        List<User> list = userService.queryAll(user);
        int count = userService.count(user);
        map.put("data",list); //数据集合
        map.put("count",count) ;//总行数
        map.put("code","0");
        map.put("msg","");

        return map ;
    }

    @RequestMapping("/deleteById")
    @ResponseBody
    public BaseMessage deleteById(Integer userId){
        BaseMessage baseMessage = new BaseMessage();
        int rows = userService.deleteById(userId);
        if(rows>0){
            baseMessage.setState(1);
            baseMessage.setMessage("删除成功!");
        }else{
            baseMessage.setState(0);
            baseMessage.setMessage("删除失败!");
        }
        return baseMessage;
    }

    /**
     * 增加或者修改
     * @param user
     * @return
     */
    @RequestMapping("/addOrUpdate")
    @ResponseBody
    public BaseMessage addOrUpdate(@RequestParam("userFile") MultipartFile mulfile,User user) throws IOException {

        String name = mulfile.getOriginalFilename() ;//得到原文件名
        if(!StringUtils.isEmpty(name)) { //如果不传图片,就不执行以下代码
            int index = name.lastIndexOf("."); //234234.4443.123.jpg
            String suf = name.substring(index);//得到后缀名
            String fileName = UUID.randomUUID().toString() + "" + suf; //ffff-22221-ffff-ff.jpg

            mulfile.transferTo(new File(saveFilePath + "/" + fileName)); //保存文件

            user.setFile("upload/" + fileName);
        }

        int rows = 0;
        if(user.getUserId()==null){
            rows=userService.add(user);
        }else{
            rows =userService.update(user);
        }
        BaseMessage bm = new BaseMessage();
        bm.setState(rows);
        return bm ;
    }

    @RequestMapping("/showUpdate")
    @ResponseBody
    public User showUpdate(Integer userId){

        return userService.queryById(userId);
    }

}
